/*
 * @Date: 2023-03-25 16:16:43
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-26 09:57:36
 * @FilePath: \A19\backend\src\api\Get\ApiGetAllHWInfo.ts
 */
import { ApiCall } from "tsrpc";
import {
  ReqGetAllHWInfo,
  ResGetAllHWInfo,
  info,
  safeStu
} from "../../shared/protocols/Get/PtlGetAllHWInfo";
import { Global } from "../../Global/index";

export default async function (
  call: ApiCall<ReqGetAllHWInfo, ResGetAllHWInfo>
) {
  // TODO
  const p1 = Global.collection("selectCourses")
    .aggregate([
      {
        $match: {
          course: call.req.course,
        },
      },
      {
        $lookup: {
          from: "users",
          localField: "student",
          foreignField: "_id",
          as: "student",
        },
      },
      {
        $unwind: "$student",
      },
      { $replaceRoot: { newRoot: "$student" } },
    ])
    .toArray();
  const p2 = Global.collection("homework")
    .aggregate([
      {
        $match: {
          course: call.req.course,
          status: "published",
          _id:{
            $in:call.req.requiredHomework
          }
        },
      },
      {
        $lookup: {
          from: "userHomework",
          localField: "_id",
          foreignField: "test",
          as: "userHomework",
        },
      },
      {
        $lookup: {
          from: "users",
          localField: "userHomework.student",
          foreignField: "_id",
          as: "student",
        },
      },
      {
        $project: {
          course: false,
          startTime: false,
          endTime: false,
          questions: false,
          status: false,
          _id: false,

          "student.email": false,
          "student.password": false,
          "student.gender": false,
          "student.portrait": false,
          "student.role": false,
          "student.school": false,
          // 'student._id':false,

          "userHomework.answers": false,
          "userHomework.submitTime": false,
          "userHomework.test": false,
          "userHomework._id": false,
        },
      },
    ])
    .toArray();

  const ret = await Promise.all([p1, p2]);
  call.succ({
    info: ret[1] as info[],
    students: ret[0] as safeStu[],
  });
}
